#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash apbs-1.3.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1
[[ "$1" = "$2" ]] && echo "构建路径与安装路径不能相同" && exit 1
buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
set -e

cd $buildpath
wget -t 10 -c https://github.com/TinkerTools/apbs-1.3/archive/refs/heads/release.zip -O $buildpath/apbs-1.3-release.zip
unzip apbs-1.3-release.zip
mv apbs-1.3-release apbs-1.3 && cd apbs-1.3
sed -i 's/x86_64/aarch64/g' `grep 'x86_64' . -lr`
./configure --enable-tinker --disable-zlib --prefix=$installpath/apbs-1.3 --with-python=/usr/bin/python2 \
CFLAGS='-DVAPBSQUIET -fopenmp' CXXFLAGS='-DVAPBSQUIET -fopenmp' FFLAGS='-DVAPBSQUIET -fopenmp' \
CC=clang CXX=clang++ F77=flang 
make && make install
#does't support multiple proc
cp -r $buildpath/apbs-1.3/contrib/lib/* $installpath/apbs-1.3/lib/
cat>"$installpath/apbs-1.3/apbs_modulefiles"<<EOF
#%Module1.0
conflict apbs
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set apbs \$pwd
setenv apbs \$apbs
setenv apbslib \$apbs/lib
prepend-path PATH \$apbs/bin
EOF
